package com.heima.search.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.AppUserThreadLocal;
import com.heima.utils.thread.WmUserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Interceptor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shiminghui
 * @date 2024/12/12 19:50
 * @description: TODO
 */
@Component
@Slf4j
public class AppTokenInterceptor implements HandlerInterceptor {
    /**
     * 前置处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的userId属性
        String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(userId)) {
            log.info("用户未登录");
            response.setStatus(401);//响应状态码
            return false;
        }
        //将用户id存入线程变量中
        ApUser apUser = new ApUser();
        apUser.setId(Integer.valueOf(userId));
        AppUserThreadLocal.setUser(apUser);


        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 后置处理
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 释放资源
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppUserThreadLocal.removeUser();//释放资源
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
